# library(haven)
# library(dplyr)
# library(foreign)
# library(expss)
# library("Hmisc")
# library(corrplot)
# library(ggplot2)
# library(weights)
packages <- c(
  "haven",
  "dplyr",
  "Hmisc",
  "corrplot",
  "weights",
  "expss"
)

for (p in packages) {
  if (!require(p, character.only = TRUE)) {
    install.packages(p, repos = "https://cloud.r-project.org")
    library(p, character.only = TRUE)
  }
}


#Read the data.


args = commandArgs(trailingOnly=TRUE)

dta = read_dta(paste(args[1],"/IHS_correlation_index_data_R.dta",sep=""))

#weights_vector <- dta %>% select(c("weights"))
#weights_vector$weights <- as.numeric(weights_vector$weights)
#dta = dta %>% select(-c("weights"))

list_labels = sapply(dta, var_lab)
names(dta) = list_labels

dta$`Firm Level Weights` <- as.numeric(dta$`Firm Level Weights`)

weights <- dta$`Firm Level Weights`
dta <- dta %>% select(-`Firm Level Weights`)

dta.rcorr = rcorr(as.matrix(dta))
dta.rcorr

#table
dta.coeff = dta.rcorr$r
dta.p = dta.rcorr$P

#graph
dta.cor = wtd.cor(dta, weight=weights)
png(height=1800, width=1800, file=paste(args[2],"/Figure_B1.png",sep=""))
corrplot(dta.coeff, tl.col="black", tl.srt=45, tl.cex = 2, type="lower", addCoef.col ='black', number.cex =2, cl.cex = 2, diag=FALSE, addrect = 3)
dev.off()
